package middleware

import (
	"encoding/json"
	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
	"shyxy-model-agent/core/http/utils"
	"shyxy-model-agent/core/types"
	"strings"
)

type UserInfo struct {
	ID     int64  `json:"id"`
	Mobile string `json:"mobile"`
	Email  string `json:"email"`
}

const (
	TokenSecret   = "Wc2q8a9y8a"
	DecryptSecret = "MmyfEFDl534tqwlLSWPQGKe0JqOBBtoy"
)

func UserJWTAuth() fiber.Handler {
	return func(c *fiber.Ctx) error {
		authHeader := c.Get(fiber.HeaderAuthorization)
		if authHeader == "" {
			return c.Status(fiber.StatusUnauthorized).SendString("Authorization header user_token is missing")
		}
		var userJWT string
		if len(authHeader) > 7 && authHeader[:7] == types.AuthorizationPrefix {
			userJWT = strings.TrimSpace(authHeader[7:])
		} else {
			return c.Status(fiber.StatusUnauthorized).SendString("Invalid Authorization header")
		}
		payload, err := utils.ParseTokenToMap(userJWT, TokenSecret)
		if err != nil {
			log.Error().Msgf("error during token parsing,err:%s", err)
		}
		userToken := payload["user"].(string)
		decrypted, err := utils.DecryptData(userToken, DecryptSecret)
		if err != nil {
			return c.Status(fiber.StatusUnauthorized).SendString("Invalid User Token")
		}
		var userInfo UserInfo
		if err := json.Unmarshal(decrypted, &userInfo); err != nil {
			return c.Status(fiber.StatusUnauthorized).SendString("unmarshal userInfo failed")
		}
		log.Info().Msgf("userInfo: %v", userInfo) //debug
		c.Locals("user", userInfo)
		return c.Next()
	}
}
